package com.hongmeng.teamwork.domain.impl;

import com.alibaba.fastjson.JSON;
import com.hongmeng.teamwork.convert.DepartmentConvert;
import com.hongmeng.teamwork.entity.vo.DepartmentVo;
import com.hongmeng.teamwork.domain.IDepartmentDomainService;
import com.hongmeng.teamwork.utils.FeishuUtil;
import com.lark.oapi.Client;
import com.lark.oapi.core.utils.Lists;
import com.lark.oapi.service.contact.v3.model.ChildrenDepartmentReq;
import com.lark.oapi.service.contact.v3.model.ChildrenDepartmentResp;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Log4j2
@Service
public class DepartmentDomainServiceImpl implements IDepartmentDomainService {

    @Resource
    private Client client;

    @Override
    public List<DepartmentVo> getDepartmentByPid(String accessToken, String departmentId) {
        ChildrenDepartmentResp resp;
        try {
            resp = client.contact().department()
                .children(ChildrenDepartmentReq.newBuilder().departmentId(departmentId).build(),
                        FeishuUtil.getRequestOptionsByAccessToken(accessToken));
        } catch (Exception e) {
            log.error("DepartmentServiceImpl.getDepartmentByPid.error: {}", e.getMessage(), e);
            throw new RuntimeException(e);
        }
        List<DepartmentVo> departmentVoList = DepartmentConvert.INSTANCE.convertRespToEntity(Lists.newArrayList(resp.getData().getItems()));
        if (log.isInfoEnabled()) {
            log.info("DepartmentServiceImpl.getDepartmentByPid.departmentList: {}", JSON.toJSONString(departmentVoList));
        }
        return departmentVoList;
    }
}
